////////////////////////////////////////////////////////////////////////////////
//
//  FLEX USER GROUP HOKURIKU
//  Copyright 2009 Flex User Group Hokuriku
//  All Rights Reserved.
// 
//  NOTICE: Flex User Group Hokuriku permits you to use, 
//  modify, and distribute this file 
//  in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
package net.fxug.hokuriku.chocolat.helper
{
    import air.update.ApplicationUpdaterUI;
    import air.update.events.UpdateEvent;

    import flash.desktop.NativeApplication;
    import flash.display.NativeWindow;
    import flash.display.Screen;
    import flash.events.ErrorEvent;
    import flash.events.Event;
    import flash.events.InvokeEvent;

    import mx.core.IMXMLObject;
    import mx.core.WindowedApplication;
    import mx.events.FlexEvent;
    import mx.logging.ILogger;

    import net.fxug.hokuriku.chocolat.dao.DatabaseManager;
    import net.fxug.hokuriku.chocolat.service.VoteManager;
    import net.fxug.hokuriku.chocolat.utils.LoggingUtil;

    /**
     * アプリケーションのメインとなるヘルパークラス
     *
     * 起動時にコマンドライン引数で-windowを与えることでデバッグウィンドウが有効となる。
     *
     * @author shoito, hikaruworld
     */
    public class SORAAIHelper implements IMXMLObject
    {
        private var view:WindowedApplication;

        private var logger:ILogger = LoggingUtil.getLogger(SORAAIHelper);

        private var appUpdater:ApplicationUpdaterUI = new ApplicationUpdaterUI();

        public function initialized(document:Object, id:String):void
        {
            this.view = document as WindowedApplication;
            this.view.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
            this.view.addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);
        }

        private function creationCompleteHandler(event:FlexEvent):void
        {
            // ロギングの設定
            LoggingUtil.setDefaultTarget();

            this.view.addEventListener(Event.CLOSE, closeHandler);

            NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, nativeApplicaiton_invokeEventHandler);
            NativeApplication.nativeApplication.addEventListener(Event.EXITING, nativeApplication_exitingEventHandler);

            checkForUpdate();
        }

        private function checkForUpdate():void
        {
            logger.info("Current version is " + getApplicationVersion());
            appUpdater.updateURL = "http://soraai.googlecode.com/files/update.xml";
            appUpdater.isCheckForUpdateVisible = false;
            appUpdater.addEventListener(UpdateEvent.INITIALIZED, appUpdaterInitializedHandler);
            appUpdater.addEventListener(ErrorEvent.ERROR, appUpdaterErrorHandler);
            appUpdater.initialize();
        }

        private function appUpdaterErrorHandler(event:ErrorEvent):void
        {
            logger.error("update error {0}", event.text);
        }

        private function appUpdaterInitializedHandler(event:UpdateEvent):void
        {
            appUpdater.checkNow();
        }

        private function getApplicationVersion():String
        {
            var appXML:XML = NativeApplication.nativeApplication.applicationDescriptor;
            var ns:Namespace = appXML.namespace();
            return appXML.ns::version;
        }

        /**
         * アプリケーション終了時に実行されるイベントハンドラ.
         * 注:開発自身がアプリケーションを終了させる場合は、Airからこのイベントが発行される訳ではないので、
         * 上記の場合は終了のタイミングでEvent.EXITINGをNativeApplicationに対してdispatchする必要がある。
         */
        private function nativeApplication_exitingEventHandler(event:Event):void
        {
            NativeApplication.nativeApplication.removeEventListener(Event.EXITING, nativeApplication_exitingEventHandler);
            //VoteManagerの終了処理
            VoteManager.getInstance().close();
            //Databaseのclose処理
            DatabaseManager.getInstance().destroy();
        }

        /**
         * アプリケーション起動時にコマンドライン引数を読み込んで処理を実行するためのイベントハンドラ。
         * @param invokeEvent flash.events.InvokeEvent
         *
         */
        private function nativeApplicaiton_invokeEventHandler(invokeEvent:InvokeEvent):void
        {
            NativeApplication.nativeApplication.removeEventListener(InvokeEvent.INVOKE, nativeApplicaiton_invokeEventHandler);
            LoggingUtil.setTarget(invokeEvent.arguments);
        }

        private function addedToStageHandler(event:Event):void
        {
            this.view.nativeWindow.x = (Screen.mainScreen.visibleBounds.width - this.view.nativeWindow.width) / 2;
            this.view.nativeWindow.y = (Screen.mainScreen.visibleBounds.height - this.view.nativeWindow.height) / 2;
        }

        private function closeHandler(event:Event):void
        {
            event.preventDefault();

            var openedWindows:Array = NativeApplication.nativeApplication.openedWindows;
            for (var i:int = openedWindows.length - 1; i >= 0; --i)
            {
                var openedWindow:NativeWindow = openedWindows[i] as NativeWindow;
                openedWindow.close();
            }
        }
    }
}